//时间都浪费在调试上了，运行要1分钟，不像h5 刷新一下就行了。是时候改变了。

//能不暴露的就不要暴露
#import "ShoppingCartView.h"
//view
#import "NewShopcartCell.h" //11-20
#import "ShopcartNoDataView.h" //1-2没有数据

//model
//#import "ShopCartModel.h"
#import "NewShopcartModel.h"


typedef NS_ENUM(NSInteger, RequestType) {
    RequestTypeNormal = 10, //常规操作
    RequestTypeRemove,//购物车被清空
};

@interface ShoppingCartView()<UITableViewDataSource,UITableViewDelegate>
@property(strong , nonatomic) UIViewController *viewController;
@property(strong , nonatomic) UITableView *myTableView;
/**数据源*/
@property (nonatomic, strong) NSMutableArray *dataArrM;
/**有用于标记购物车被清空*/
@property (nonatomic, assign) RequestType requesType;
/**1-2没有数据*/
@property (nonatomic, strong) ShopcartNoDataView *nodataView;

@end

@implementation ShoppingCartView

#pragma mark - layout
- (void)layoutSubviews {
    [super layoutSubviews];
    
    //根据cell的个数动态的就算tableView的高度,有困难
    [self.myTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.mas_left);
        make.right.equalTo(self.mas_right);
        make.bottom.equalTo(self.mas_bottom);
        make.height.mas_equalTo(150);
    }];

    //1-2
    self.nodataView.frame = self.myTableView.bounds;
}

#pragma mark - getter
- (UITableView *)myTableView{
    
    if (!_myTableView) {
//        CGFloat sh = self.bounds.size.height;
        //表格的高度是:200 frame的布局的计算
        
        //y:高度200 iphonx底部状态栏高度34 - 底部view的高度。
//        CGFloat h = 200 +
//        CGFloat y = sh - 150 - FD_TabbarSafeBottomMargin;
//        CGRect *tvFrame = CGRectMake(0, y, SCREEN_WIDTH, 150);
        //不给frame,用masonry来进行布局。
        _myTableView = [[UITableView alloc] initWithFrame:CGRectZero style:(UITableViewStylePlain)];
        _myTableView.delegate = self;
        _myTableView.dataSource = self;
        
        //注册cell、
        [_myTableView registerClass:[NewShopcartCell class] forCellReuseIdentifier:@"NewShopcartCell"];
        
        [self addSubview:_myTableView];
        _myTableView.tableFooterView = [UIView new];
        _myTableView.separatorStyle = UITableViewCellSeparatorStyleNone; //取消线
        
        //背景颜色
        _myTableView.backgroundColor = [UIColor whiteColor];
        
        //隐藏内容区域线
        _myTableView.showsVerticalScrollIndicator = NO;
    }
    
    return _myTableView;
}


- (ShopcartNoDataView *)nodataView {
    if (!_nodataView) {
        _nodataView = [[ShopcartNoDataView alloc] initWithFrame:CGRectZero];
        _nodataView.hidden = YES; //默认隐藏
    }
    return _nodataView;
}

- (NSMutableArray *)dataArrM {
    if (!_dataArrM) {
        _dataArrM = [NSMutableArray array];
    }
    return _dataArrM;
}

#pragma mark -- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    FDLog(@"个数:%ld",self.dataArrM.count);
    return self.dataArrM.count; //不解析直接取
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NewShopcartCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewShopcartCell"];
    //给cell赋值
    NewShopcartModel *currentModel = self.dataArrM[indexPath.row];
    cell.model = currentModel;
    
    
    FDWeakSelf;
    __block NSInteger count = [currentModel.quantity integerValue]; //数量
    //事件回调
    //减➖
    cell.newshopcartCellMinuBlock = ^{
        if (count > 1) {
            count -=1;
            [weakSelf requestUpdateCartQuantity:@(count) cartId:currentModel.cartId];
        }else { // 删除商品
            [weakSelf requestCartRemoveCartId:currentModel.cartId];
            [JRToast showWithText:@"删除商品"];
        }
        
        FDLog(@"当前数量:%ld",count);
    };
    

    //加➕
    cell.newshopcartCellAddBlock = ^{
        count += 1;
        [weakSelf requestUpdateCartQuantity:@(count) cartId:currentModel.cartId];
        FDLog(@"当前数量:%ld",count);
    };
    return cell;
}

#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NewShopcartModel *model = self.dataArrM[indexPath.row];
    return model.cellHeight;
}


#pragma mark - 购物车接口 
- (void)addShoppingCartView:(UIViewController *)vc{
    _viewController = vc;
    [vc.view addSubview:self];
    [self.myTableView addSubview:self.nodataView]; //1-2
    [self requestObtainCartListWithTag:(RequestTypeNormal)]; //请求数据
}

- (void)removeSubView:(UIViewController *)vc{
    UIView * v = [vc.view viewWithTag:111];
    [v removeFromSuperview];
    [self removeFromSuperview];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"FootView" object:nil];
    [self removeSubView:_viewController];
}



#pragma mark - 网络请求：修改数量删除商品
//!!!!:获取购物车数据

/**
 Description

 @param tag 用于标记是移除商品，如果购物车q被清空就让告知控制器 让self 消失
 */
- (void)requestObtainCartListWithTag:(RequestType)tag {
    
    [self.dataArrM removeAllObjects];
    
    [MBProgressHUD fd_showHUDToView:self]; //加载中...
    
    [FDHttpAPi requestSYUserCartListSuccessBlock:^(id responseObjc) {
        [MBProgressHUD fd_hideHUDFromView:self]; //加载完成
        
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) {
            
            NSArray *dataArr = responseObjc[@"data"];
            
            //11-20用于标记购物车被清空
            if ((tag == RequestTypeRemove) &&  dataArr.count == 0) { //购物车被清空
                if ([self.delegate respondsToSelector:@selector(shoppingCartHaveBeClean)]) {
                    [self.delegate shoppingCartHaveBeClean];
                    
                    //2019-2-16 购物车被清空也要更新总价。计算总价并触发回调，告知控制器更新数据
                    [self countTotalPriceWithArr:self.dataArrM];
                }
                
                return ; //购物车都清空了, 下面的事也不用做了,下班了,早点回去休息。
            }
            
            
            for (NSDictionary *dic in dataArr) { //只转一层
                NewShopcartModel *model = [NewShopcartModel mj_objectWithKeyValues:dic];
                [self.dataArrM addObject:model];
            }

            //计算总价并触发回调，告知控制器更新数据
            [self countTotalPriceWithArr:self.dataArrM];
            
            //回调主线程中刷新
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.myTableView reloadData];
                if (self.dataArrM.count) {
                    self.nodataView.hidden = YES;
                }else {
                    self.nodataView.hidden = NO;
                }
            });
        }else {
            [JRToast showWithText:responseObjc[describe]];
            [MBProgressHUD fd_hideHUDFromView:self]; //加载完成
        }
    } failBlock:^(NSError *error) {
        FDLog(@"%@",[error localizedDescription]);
    }];
}
//!!!!:修改购物车数量
- (void)requestUpdateCartQuantity:(NSNumber *)quantity cartId:(NSNumber *)cartId {
    FDLog(@"数量:%@---购物车id:%@",quantity,cartId);
    [FDHttpAPi requestSYUserCartUpdateQuantity:quantity cartId:cartId successBlock:^(id responseObjc) {
        //暂时处理处理方式:不做处理 请求失败就修改数据 10-25
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) {

            [self requestObtainCartListWithTag:(RequestTypeNormal)];
        }else {
            [JRToast showWithText:responseObjc[describe]];
        }
    } failBlock:^(NSError *error) {
        FDLog(@"%@",[error localizedDescription]);
    }];
}
//!!!!:移除购物车
- (void)requestCartRemoveCartId:(NSNumber *)cartId {
    [FDHttpAPi requestSYUserCartRemoveCartId:cartId successBlock:^(id responseObjc) {

        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) {

            //刷新数据:此时 ShoppingCartView 对象是存在的可以调接口然后 在进行刷新
            [self requestObtainCartListWithTag:(RequestTypeRemove)];
        }else {
            [JRToast showWithText:responseObjc[describe]];
        }
    } failBlock:^(NSError *error) {
        FDLog(@"%@",[error localizedDescription]);
    }];
}


#pragma mark - 重写setter 方法进行赋值

#pragma mark - 数据解析
- (void)assembleDataArr:(NSArray *)arr {

}

//!!!!:计算总价并触发代理 告知控制器
- (void)countTotalPriceWithArr:(NSArray *)arr {
    
    CGFloat sumPrice = 0.0;
    for (NewShopcartModel *model in arr) {
        sumPrice += model.totalcurrentPrice * [model.quantity floatValue];
    }    
    //通知控制器并告知总价
    if ([self.delegate respondsToSelector:@selector(shoppingCartViewUpdateTotalPrice:)]) {
        [self.delegate shoppingCartViewUpdateTotalPrice:sumPrice];
    }
}

#pragma mark - 计算总金额。

@end

//bug只有一个的时候问题很多,无法从购物车中移除。 不是办法的办法, ✅

